package com.xvyy.tingshu.album.service.impl;

import com.xvyy.tingshu.album.mapper.AlbumInfoMapper;
import com.xvyy.tingshu.album.mapper.TrackInfoMapper;
import com.xvyy.tingshu.album.mapper.TrackStatMapper;
import com.xvyy.tingshu.album.service.TrackInfoService;
import com.xvyy.tingshu.album.service.VodService;
import com.xvyy.tingshu.common.constant.SystemConstant;
import com.xvyy.tingshu.common.execption.TsException;
import com.xvyy.tingshu.common.result.Result;
import com.xvyy.tingshu.common.util.AuthContextHolder;
import com.xvyy.tingshu.model.album.AlbumInfo;
import com.xvyy.tingshu.model.album.TrackInfo;
import com.xvyy.tingshu.model.album.TrackStat;
import com.xvyy.tingshu.query.album.TrackInfoQuery;
import com.xvyy.tingshu.user.client.UserInfoFeignClient;
import com.xvyy.tingshu.vo.album.*;
import com.xvyy.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;


import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

    @Autowired
    private TrackInfoMapper trackInfoMapper;

    @Autowired
    private VodService vodService;

    @Autowired
    private TrackStatMapper trackStatMapper;

    @Autowired
    private AlbumInfoMapper albumInfoMapper;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveTrackInfo(TrackInfoVo trackInfoVo) {

        // 0. 获取当前代理对象，以便在同一个类中调用其他方法
        TrackInfoServiceImpl proxy = (TrackInfoServiceImpl) AopContext.currentProxy();
        Long userId = AuthContextHolder.getUserId();
        // 1. 保存歌曲信息
        TrackInfo trackInfo = new TrackInfo();
        // 1.1 基本属性通过拷贝赋值
        // trackInfoVo拷贝到trackInfo中
        BeanUtils.copyProperties(trackInfoVo, trackInfo);
        // 1.2 其他属性手动赋值
        trackInfo.setUserId(userId);// 歌曲上传者ID
        trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);// 是否审核通过
        // 找到当前用户上传的最后一条歌曲信息的orderNum，然后+1
        // 查询当前用户上传的所有歌曲，并按照orderNum降序排序
        LambdaQueryWrapper<TrackInfo> queryWrapper = new LambdaQueryWrapper<TrackInfo>()
                .eq(TrackInfo::getAlbumId, trackInfoVo.getAlbumId())// 查询当前专辑下的所有歌曲信息
                .orderByDesc(TrackInfo::getOrderNum)// 按照orderNum降序排序
                .last("limit 1");// limit 1 只查询一条数据
        TrackInfo maxOrderNumTrackInfo = trackInfoMapper.selectOne(queryWrapper);
        Integer orderNum = maxOrderNumTrackInfo == null ? 1 : maxOrderNumTrackInfo.getOrderNum() + 1;
        trackInfo.setOrderNum(orderNum);// 设置歌曲在专辑中的顺序号
        trackInfo.setMediaFileId(trackInfoVo.getMediaFileId());// 声音VOD中的ID
        // 1.3 查询VOD响应的媒体信息，并赋值给歌曲信息
        TrackMediaInfoVo trackMediaInfoVo = vodService.getTrackMediaInfoVo(trackInfoVo.getMediaFileId());
        if (trackMediaInfoVo != null) {
            trackInfo.setMediaUrl(trackMediaInfoVo.getMediaUrl());// 声音播放地址
            trackInfo.setMediaType(trackMediaInfoVo.getType());// 声音类型
            trackInfo.setMediaDuration(BigDecimal.valueOf(trackMediaInfoVo.getDuration()));// 声音时长
            trackInfo.setMediaSize(trackMediaInfoVo.getSize());// 声音大小
        }
        // 保存媒体信息到数据库
        trackInfoMapper.insert(trackInfo);
        // 2. 保存声音的统计信息 用代理对象调用initTrackStat方法，初始化歌曲统计信息
        proxy.initTrackStat(trackInfo.getId());
        // 3. 修改声音包含的声音集数
        // 4. 修改声音所属的专辑集数
        Long albumId = trackInfo.getAlbumId();
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        // 4.1 判断专辑是否为空
        // 不空，查询当前专辑包含的歌曲数量，然后+1
        if (albumInfo != null) {
            albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() + 1);
        }
        // 4.2 更新专辑信息
        albumInfoMapper.updateById(albumInfo);
    }


    @Override
    public IPage<TrackListVo> findUserTrackPage(IPage<TrackListVo> trackInfoVoIPage, TrackInfoQuery trackInfoQuery) {
        trackInfoQuery.setUserId(AuthContextHolder.getUserId()); // 给条件对象赋值用户id
        return trackInfoMapper.findUserTrackPage(trackInfoVoIPage, trackInfoQuery);
    }

    @Override
    public TrackInfo getTrackInfo(Long trackId) {
        return trackInfoMapper.selectById(trackId);
    }

    @Override
    public void updateTrackInfoByTrackId(Long trackId, TrackInfoVo trackInfoVo) {
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
        if (trackInfo == null) {
            throw new TsException(201, "声音不存在");
        }
        String oldMediaFileId = trackInfo.getMediaFileId();
        String newMediaFileId = trackInfoVo.getMediaFileId();
        BeanUtils.copyProperties(trackInfoVo, trackInfo);

        // 1. 如果声音文件发生变化，则需要重新上传声音到VOD
        if (!StringUtils.isEmpty(newMediaFileId) && !oldMediaFileId.equals(newMediaFileId)) {
            // 获取声音信息
            TrackMediaInfoVo trackMediaInfoVo = vodService.getTrackMediaInfoVo(newMediaFileId);
            if (trackMediaInfoVo != null) {
                trackInfo.setMediaUrl(trackMediaInfoVo.getMediaUrl());// 声音播放地址
                trackInfo.setMediaType(trackMediaInfoVo.getType());// 声音类型
                trackInfo.setMediaDuration(BigDecimal.valueOf(trackMediaInfoVo.getDuration()));// 声音时长
                trackInfo.setMediaSize(trackMediaInfoVo.getSize());// 声音大小
            }
        }
        // 更新数据库
        trackInfoMapper.updateById(trackInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeTrackInfoByTrackId(Long trackId) {
        // 0. 根据trackId查询旧的声音信息
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
        if (trackInfo == null) {
            throw new TsException(201, "声音不存在");
        }

        // 1. 修改专辑包含的声音数量
        Long albumId = trackInfo.getAlbumId();
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        // 1.1 判断专辑是否为空
        if (albumInfo == null) {
            throw new TsException(201, "专辑不存在");
        }
        // 1.2 查询当前专辑包含的歌曲数量，然后-1
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() - 1);
        // 1.3 更新专辑信息

        int ii = albumInfoMapper.updateById(albumInfo);
        if (ii < 1) {
            throw new TsException(201, "专辑不存在");
        }
        // 2. 删除声音基本信息
        trackInfoMapper.deleteById(trackId);

        // 2. 删除声音信息
        trackStatMapper.delete(new LambdaQueryWrapper<TrackStat>().eq(TrackStat::getTrackId, trackId));

        // 3. 删除VOD中的声音信息
        vodService.removeVodFile(trackInfo.getMediaFileId());

    }

    @Override
    public IPage<AlbumTrackListVo> findAlbumTrackPage(IPage<AlbumTrackListVo> trackInfoVoIPage, Long albumId) {

        IPage<AlbumTrackListVo> result = new Page<>();

        // 1. 根据专辑id查询声音列表 调用完mapper , isShowPaidMark属性都是false
        IPage<AlbumTrackListVo> albumTrackListFromDB = trackInfoMapper.findAlbumTrackPage(trackInfoVoIPage, albumId);

        // 2. 处理列表中每一个声音的isShowPaidMark属性(true/false)
        // 2.1 根据专辑id查询专辑对象
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        Assert.notNull(albumInfo, "专辑不存在");
        // 2.2 获取专辑的付费类型(0101-免费、0102-vip免费、0103-付费)
        String payType = albumInfo.getPayType();
        // 2.3 获取专辑的价格类型(0201-单集 0202-整专辑)
        String priceType = albumInfo.getPriceType();
        // 2.4 获取专辑的免费声音集数
        Integer tracksForFree = albumInfo.getTracksForFree();
        // 2.5 获取当前用户
//        Long userId = albumInfo.getUserId();
        Long userId = AuthContextHolder.getUserId();
        // 2.6 根据 专辑 的付费类型，判断如何返回声音列表数据
/*        switch (payType) {
            case "0101":
                // 2.6.1 免费 --> 所有声音都显示免费图标
                result = albumTrackListFromDB;
                break;
            case "0102":
                // 2.6.2 vip免费 -->  前5个声音免费
                result = dealPayTypeVipFree(priceType, tracksForFree, albumTrackListFromDB, userId, albumId);
                break;
            case "0103":
                //  2.6.3 付费专辑  -->  前5个声音免费
                result = dealPayTypeNeedPaid(priceType, tracksForFree, albumTrackListFromDB, userId, albumId);
                break;
        }*/
        // 2.6.1 免费 --> 所有声音都显示免费图标
        // 2.6.2 vip免费 -->  前5个声音免费
        //  2.6.3 付费专辑  -->  前5个声音免费
        switch (payType) {
            // 2.6.1 免费 --> 所有声音都显示免费图标
            case "0101" -> result = albumTrackListFromDB;
            // 2.6.2 vip免费 -->  前5个声音免费
            case "0102" -> result = dealPayTypeVipFree(priceType, tracksForFree, albumTrackListFromDB, userId, albumId);
            //  2.6.3 付费专辑  -->  前5个声音免费
            case "0103" ->
                    result = dealPayTypeNeedPaid(priceType, tracksForFree, albumTrackListFromDB, userId, albumId);
            // 2.6.4 其他情况，抛出异常
            default -> throw new TsException(201, "付费类型不存在");
        }

        // 3. 返回声音列表(处理完付费图标)
        return result;
    }

    @Override
    public TrackStatVo getTrackStatVoByTrackId(Long trackId) {
        return trackStatMapper.getTrackStatVoByTrackId(trackId);
    }

    @Override
    public List<Map<String, Object>> findUserTrackPaidList(Long currentTrackId) {
        ArrayList<Map<String, Object>> resultListMap = new ArrayList<>();
        // 1. 登录用户id
        Long userId = AuthContextHolder.getUserId();
        // 2. 获取声音对象
        TrackInfo trackInfo = trackInfoMapper.selectById(currentTrackId);
        if (trackInfo == null) {
            throw new TsException(201, "购买声音不存在");
        }
        // 3. 获取专辑对象id
        Long albumId = trackInfo.getAlbumId();
        // 4. 获取专辑对象
        AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfo.getAlbumId());
        if (albumInfo == null) {
            throw new TsException(201, "购买声音对应专辑不存在");
        }
        // 5. 获取声音价格
        BigDecimal price = albumInfo.getPrice();
        // 6. 获取声音序列号
        Integer orderNum = trackInfo.getOrderNum();
        // 7. 查询当前声音之后所有数据
        List<TrackInfo> trackInfoList = trackInfoMapper.selectList(new LambdaQueryWrapper<TrackInfo>()
                .eq(TrackInfo::getAlbumId, albumId).gt(TrackInfo::getOrderNum, orderNum).orderByAsc(TrackInfo::getOrderNum)
                .last("limit 50"));// 只查询50条数据，防止数据库压力过大
        // 8. 查询当前用户已经购买的转及声音id
        Result<Map<Long, String>> userPaidAlbumTrackMapResult = userInfoFeignClient.getUserPaidAlbumTrackList(userId, albumId);
        Map<Long, String> userPaidAlbumTrackMapData = userPaidAlbumTrackMapResult.getData();
        Assert.notNull(userPaidAlbumTrackMapData, "远程调用用户微服务获取该购买专辑下的声音列表失败");
        // 9. 过滤掉已经购买的声音
        List<Long> rellayCanShowTrackIdList = trackInfoList.stream().map(TrackInfo::getId).filter(trackId -> StringUtils.isEmpty(userPaidAlbumTrackMapData.get(trackId))).collect(Collectors.toList());
        // 10. 展示购买声音
        // 10.1 购买集数

        int totalSize = rellayCanShowTrackIdList.size();
        // 10.2 展示块数
        // 展示本集：
        HashMap<String, Object> mapFirst = new HashMap();
        mapFirst.put("name", "本集");// 本集名称
        mapFirst.put("price", price);// 本集的价格展示
        mapFirst.put("trackCount", 0);//集数不展示，用于区分的
        resultListMap.add(mapFirst);
        // 10.3 展示的块数
        int blockSize = totalSize % 10 == 0 ? totalSize / 10 : totalSize / 10 + 1;
        for (int i = 1; i <= blockSize; i++) {
            int count = i * 10;
            if (count >= totalSize) {
                Map<String, Object> mapSecond = new HashMap<>();
                mapSecond.put("name", "后" + totalSize + "集"); // 名字展示
                mapSecond.put("price", price.multiply(new BigDecimal(totalSize)));// 价格展示
                mapSecond.put("trackCount", totalSize);//集数不展示，用于区分的
                resultListMap.add(mapSecond);
                break;
            }
            Map<String, Object> mapThird = new HashMap<>();
            mapThird.put("name", "后" + count + "集"); // 名字展示
            mapThird.put("price", price.multiply(new BigDecimal(count)));// 价格展示
            mapThird.put("trackCount", count);//集数不展示，用于区分的
            resultListMap.add(mapThird);
        }
        return resultListMap;
    }

    /**
     * @param albumId
     * @param userId
     * @param trackCount
     * @param trackId
     * @return
     */
    @Override
    public Result<List> getPaidTrackAndFilterCanPayTrack(Long albumId, Long userId, Integer trackCount, Long trackId) {
        List<TrackInfo> result = new ArrayList<>();
        // 1.查询当前用户买过的专辑下的声音
        Result<Map<Long, String>> userPaidAlbumTrackListResult = userInfoFeignClient.getUserPaidAlbumTrackList(userId, albumId);
        Map<Long, String> userPaidAlbumTrackListData = userPaidAlbumTrackListResult.getData();
        Assert.notNull(userPaidAlbumTrackListData, "远调user微服务，获取用户购买过的专辑下的声音信息失败");
        // 2.查询要买的声音
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
        // 2.1 如果trackCount为0，则只返回要买的声音
        if (trackCount == 0) {
            result.add(trackInfo);
        } else {
            // 2.2 如果trackCount不为0，则返回要买的声音和后面的声音
            result = trackInfoMapper.selectList(new LambdaQueryWrapper<TrackInfo>()
                    .eq(TrackInfo::getAlbumId, albumId)
                    .gt(TrackInfo::getOrderNum, trackInfo.getOrderNum())
                    .last("limit " + trackCount)
                    .orderByAsc(TrackInfo::getOrderNum));
        }
        // 3.过滤已经购买的声音
        List<Long> longs = new ArrayList<>();
        for (TrackInfo trackInfoFor : result) {
            if (!org.springframework.util.StringUtils.isEmpty(userPaidAlbumTrackListData.get(trackInfoFor.getId()))) {
                longs.add(trackInfoFor.getId());
                return Result.build(longs, 400, "你已经购买过该声音");
            }
        }
        // 4.返回声音列表
        return Result.ok(result);
    }
/*    @Override
    public Result<List> getPaidTrackAndFilterCanPayTrack(Long albumId, Long userId, Integer trackCount, Long trackId) {
        List<TrackInfo> result = new ArrayList<>();

        // 1. 查询当前用户购买的专辑下的声音
        Result<Map<Long, String>> userPaidAlbumTrackListResult = userInfoFeignClient.getUserPaidAlbumTrackList(userId, albumId);
        Map<Long, String> userPaidAlbumTrackListData = userPaidAlbumTrackListResult.getData();
        Assert.notNull(userPaidAlbumTrackListData, "远调user微服务，获取用户购买过的专辑下的声音信息失败");

        // 2. 查询要买的声音
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);

        // 3. 根据trackCount决定返回的声音列表
        List<TrackInfo> availableTracks = new ArrayList<>();
        if (trackCount == 0) {
            availableTracks.add(trackInfo); // 如果trackCount为0，返回单个要购买的声音
        } else {
            // 否则，查询专辑中从当前trackId开始的后续声音
            availableTracks = trackInfoMapper.selectList(new LambdaQueryWrapper<TrackInfo>()
                    .eq(TrackInfo::getAlbumId, albumId)
                    .gt(TrackInfo::getOrderNum, trackInfo.getOrderNum())
                    .orderByAsc(TrackInfo::getOrderNum)
                    .last("limit " + (trackCount * 2))); // 提取两倍数量的声音（多一些候选，避免过滤后不足）
        }

        // 4. 筛选出未购买的声音
        List<TrackInfo> unPurchasedTracks = new ArrayList<>();
        for (TrackInfo track : availableTracks) {
            if (org.springframework.util.StringUtils.isEmpty(userPaidAlbumTrackListData.get(track.getId()))) {
                unPurchasedTracks.add(track);
            }
        }

        // 5. 如果未购买的声音数量小于trackCount，则返回已购买的声音ID
        if (unPurchasedTracks.size() < trackCount) {
            List<Long> purchasedTrackIds = new ArrayList<>();
            for (TrackInfo track : availableTracks) {
                if (!org.springframework.util.StringUtils.isEmpty(userPaidAlbumTrackListData.get(track.getId()))) {
                    purchasedTrackIds.add(track.getId());
                }
            }
            return Result.build(purchasedTrackIds, 400, "你已经购买过部分声音");
        }

        // 6. 如果有足够的未购买声音，返回前trackCount个
        result = unPurchasedTracks.subList(0, trackCount);
        return Result.ok(result);
    }*/


    /**
     * vip免费专辑的处理逻辑
     *
     * @param priceType
     * @param tracksForFree
     * @param albumTrackListFromDB
     * @param userId
     * @param albumId
     * @return
     */
    private IPage<AlbumTrackListVo> dealPayTypeVipFree(String priceType, Integer tracksForFree, IPage<AlbumTrackListVo> albumTrackListFromDB, Long userId, Long albumId) {
        // 1. 判断当前用户是否存在
        if (userId == null) {
            // 1.1 如果用户不存在，返回免费集数声音列表
            List<AlbumTrackListVo> freeAlbumTrackListVo = albumTrackListFromDB.getRecords()
                    .stream()
                    .filter(albumTrackListVo -> albumTrackListVo.getOrderNum() <= tracksForFree)
                    .collect(Collectors.toList());

            return albumTrackListFromDB.setRecords(freeAlbumTrackListVo);
        }

        // 1.2 如果用户存在
        Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(userId);
        UserInfoVo userInfoVoData = userInfoVoResult.getData();
        Assert.notNull(userInfoVoResult, "用户不存在");
        Integer isVip = userInfoVoData.getIsVip();// 用户是否为VIP会员
        Date vipExpireTime = userInfoVoData.getVipExpireTime();//当前VIP到期时间，即失效时间

        // 1.2.1 如果用户不是vip，或者vip已经过期，则返回免费集数声音列表，免费之外（未购买的）显示付费
        if ("0".equals(isVip.toString()) || "1".equals(isVip.toString()) && vipExpireTime.before(new Date())) {
            return getReallyShowTrackListVoIpage(priceType, tracksForFree, albumTrackListFromDB, userId, albumId);
        } else {
            // 1.2.2 如果用户是vip，并且没有过期，直接返回声音列表
            return albumTrackListFromDB;
        }

    }

    /**
     * 付费专辑的处理逻辑
     *
     * @param priceType
     * @param tracksForFree
     * @param albumTrackListFromDB
     * @param userId
     * @param albumId
     * @return
     */
    private IPage<AlbumTrackListVo> getReallyShowTrackListVoIpage(String priceType, Integer tracksForFree, IPage<AlbumTrackListVo> albumTrackListFromDB, Long userId, Long albumId) {
        // 如果不是vip
        if ("0201".equals(priceType)) {//判断单集付费：0201-单集
            // 1.1 获取用户购买的声音列表
            Result<Map<Long, String>> userIsPaidAlbumTrackListResult = userInfoFeignClient.getUserPaidAlbumTrackList(userId, albumId);
            Map<Long, String> userIsPaidAlbumTrackListMapData = userIsPaidAlbumTrackListResult.getData();
            Assert.notNull(userIsPaidAlbumTrackListMapData, "远程调用用户微服务获取该购买专辑下的声音列表失败");
            // 1.2 过滤出用户购买的声音列表，其余显示付费图标
            List<AlbumTrackListVo> realShowTrackList = albumTrackListFromDB.getRecords()
                    .stream()
                    .map(albumTrackListVo -> {
                        if (StringUtils.isEmpty(userIsPaidAlbumTrackListMapData.get(albumTrackListVo.getTrackId())) && albumTrackListVo.getOrderNum() > tracksForFree) {
                            // 1.2.1 没有买过
                            albumTrackListVo.setIsShowPaidMark(true);
                        }
                        return albumTrackListVo;
                    })
                    .collect(Collectors.toList());
            return albumTrackListFromDB.setRecords(realShowTrackList);
        } else {//判断整张专辑付费：0202-整专辑
            // 2.1 获取用户买过的专辑列表
            Result<Boolean> userPaidAlbumResult = userInfoFeignClient.getUserPaidAlbum(userId, albumId);
            Boolean isPaidUserPaidAlbumData = userPaidAlbumResult.getData();
            Assert.notNull(isPaidUserPaidAlbumData, "远程调用用户微服务获取用户购买专辑信息失败");
            if (isPaidUserPaidAlbumData) {
                // 2.2 买过直接返回
                return albumTrackListFromDB;
            }
            // 2.3 没买，过滤出用户购买的声音列表，其余显示付费图标
            List<AlbumTrackListVo> realShowTrackList = albumTrackListFromDB
                    .getRecords().stream().map(albumTrackListVo -> {
                        if (albumTrackListVo.getOrderNum() > tracksForFree) {
                            albumTrackListVo.setIsShowPaidMark(true);
                        }
                        return albumTrackListVo;
                    }).collect(Collectors.toList());
            // 3. 返回声音列表(处理完付费图标)
            return albumTrackListFromDB.setRecords(realShowTrackList);
        }
    }

    /**
     * 付费专辑的处理逻辑
     *
     * @param priceType
     * @param tracksForFree
     * @param albumTrackListFromDB
     * @param userId
     * @param albumId
     * @return
     */
    private IPage<AlbumTrackListVo> dealPayTypeNeedPaid(String priceType, Integer tracksForFree, IPage<AlbumTrackListVo> albumTrackListFromDB, Long userId, Long albumId) {

        // 1. 用户是否登录
        if (null == userId) {
            List<AlbumTrackListVo> freeAlbumTrackListVo = albumTrackListFromDB
                    .getRecords().stream()
                    .filter(albumTrackListVo -> albumTrackListVo.getOrderNum() <= tracksForFree)
                    .collect(Collectors.toList());
            return albumTrackListFromDB.setRecords(freeAlbumTrackListVo);
        }
        // 2. 用户登录了，判断是否购买过该专辑
        return getReallyShowTrackListVoIpage(priceType, tracksForFree, albumTrackListFromDB, userId, albumId);
    }


    @Transactional(rollbackFor = Exception.class)
    public void initTrackStat(Long trackId) {
        ArrayList<String> trackStatList = new ArrayList<>();
        trackStatList.add(SystemConstant.TRACK_STAT_PLAY);
        trackStatList.add(SystemConstant.TRACK_STAT_COLLECT);
        trackStatList.add(SystemConstant.TRACK_STAT_PRAISE);
        trackStatList.add(SystemConstant.TRACK_STAT_COMMENT);
        for (String trackStatType : trackStatList) {
            TrackStat trackStat = new TrackStat();
            trackStat.setTrackId(trackId);
            trackStat.setStatType(trackStatType);
            trackStat.setStatNum(0);
            trackStatMapper.insert(trackStat);
        }
    }

}
